<?php
// sleep(1);
/*
  Compatibility: php 5.4+
        WebSite: https://codding.cn
         GitHub: https://github.com/zhaixingfy
         Author: 摘星fy
         Editor: SublimeText
           Goal: To be the world's best database dev tool
           Date: 2024-5-21 23:26:36
             vx: y273259755
             qq: 273259755
*/

header('Access-Control-Allow-Origin: *');
error_reporting(1);
define('ROOT_PATH', substr($path, 0, strrpos($path, '/')));
define('DB_HOST', $_REQUEST['dbHost']);
define('DB_USER', $_REQUEST['dbUser']);
define('DB_PWD', $_REQUEST['dbPwd']);
define('CUR_DB', $_REQUEST['curDB']);
define('CUR_TABLE', $_REQUEST['curTable']);

$conn = new mysqli(DB_HOST, DB_USER, DB_PWD);

if (CUR_DB) $conn->query('use '.CUR_DB);

function now() {
  return intval(microtime(true) * 1000);
}

function err($code, $msg) {
  // JSON_UNESCAPED_UNICODE
  echo json_encode(['errCode' => $code, 'errMsg' => $msg], 256);
  exit;
}

function res($data) {
  echo json_encode(['data' => $data], 256);
  exit;
}

function query($sql) {
  global $conn;
  $handler = $conn->query($sql);
  return $handler;
}

function queryRow($sql) {
  $handler = query($sql);
  return $handler ? $handler->fetch_assoc() : null;
}

function queryList($sql) {
  $handler = query($sql);
  if (!$handler) return [];
  $result = [];

  while ($row = $handler->fetch_assoc()) {
    $result[] = $row;
  }

  return $result;
}

switch ($_REQUEST['a']) {
  case 'ls-def':
    res([
      'time' => now(),
      'serverLang' => 'php',
      'server' => $_SERVER,
      'gs' => queryList('SHOW GLOBAL STATUS'),
      'vars' => queryList('SHOW VARIABLES'),
      'engines' => queryList('SHOW ENGINES'),
      'charset' => queryList('SHOW CHARACTER SET'),
      'collation' => queryList('SHOW COLLATION'),
      'php_ini' => ini_get_all(),
    ]);
    break;
  case 'ls-db':
    res(array_map(function($row) {
      return $row['Database'];
    }, queryList('SHOW DATABASES')));
    break;
  case 'ls-table':
    $sql = 'SHOW CREATE DATABASE `'.CUR_DB.'`';
    $handler = $conn->query($sql);

    res([
      'scDB' => $handler ? $handler->fetch_assoc()['Create Database'] : $sql.' 获取失败',
      'list' => array_map(function($row) { return $row['Tables_in_'.CUR_DB]; }, queryList('SHOW TABLES')),
    ]);
    break;
  case 'ls-field':
    res([
      'scTable' => queryRow('SHOW CREATE TABLE '.CUR_TABLE),
      'list' => queryList('DESC '.CUR_TABLE),
    ]);
    break;
  case 'ls-data':
    $pageCur = (int)$_REQUEST['pageCur'];
    $pageSize = (int)$_REQUEST['pageSize'];
    $start = $pageCur * $pageSize;

    res([
      'total' => intval(queryRow("SELECT count(*) AS total FROM ".CUR_TABLE)['total']),
      'list' => queryList("SELECT * FROM ".CUR_TABLE." LIMIT $start, $pageSize"),
    ]);
    break;
  default:
    err(2, 'uncaught action: '.$_REQUEST['a']);
    break;
}
